Minimum depth of binary tree¶
Time: O(N); Space: O(H); easy
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note:
A leaf is a node with no children.
Example 1:
Input: root = None
Output: 0
Example 2:
Input: root = {TreeNode} [3,9,20,None,None,15,7]
3
/ \
9 20
/ \
15 7
Output: 2
Example 3:
Input: root = {TreeNode} [1,None,2,3]
Output: 3
Explanation:
1
\
2
/
3
it will be serialized {1,#,2,3}
[1]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
[2]:
class Solution1(object):
"""
Time: O(N)
Space: O(H), H is height of binary tree
"""
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
[8]:
s = Solution1()
root = None
assert s.minDepth(root) == 0
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
assert s.minDepth(root) == 2
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
assert s.minDepth(root) == 3